﻿/**************************************************************
 * 命名空间：Sgr.MediatR.Behaviors
 * 创建时间：2023/8/18 9:31:51
 * 描述：MediatR请求日志行为，用于记录请求处理的生命周期
 **************************************************************/

using Microsoft.Extensions.Logging;
using MediatR;
using Sgr.Utilities;

namespace Sgr.MediatR.Behaviors
{
    /// <summary>
    /// MediatR请求日志行为
    /// </summary>
    /// <typeparam name="TRequest">请求类型</typeparam>
    /// <typeparam name="TResponse">响应类型</typeparam>
    public class LoggingBehavior<TRequest, TResponse> : IPipelineBehavior<TRequest, TResponse> where TRequest : IRequest<TResponse>
    {
        private readonly ILogger<LoggingBehavior<TRequest, TResponse>> _logger;

        public LoggingBehavior(ILogger<LoggingBehavior<TRequest, TResponse>> logger) => _logger = logger;

        /// <summary>
        /// 处理请求并记录日志
        /// </summary>
        /// <param name="request">请求对象</param>
        /// <param name="next">下一个处理委托</param>
        /// <param name="cancellationToken">取消令牌</param>
        /// <returns>响应对象</returns>
        public async Task<TResponse> Handle(TRequest request, RequestHandlerDelegate<TResponse> next, CancellationToken cancellationToken)
        {
            string typeName = TypeHelper.GetGenericTypeName(typeof(TRequest));
            _logger.LogInformation("MediatR 开始处理命令 {CommandName}（参数：{@Command}）", typeName, request);

            var response = await next();

            _logger.LogInformation("MediatR 命令 {CommandName} 处理完成 - 响应：{@Response}", typeName, response);

            return response;
        }
    }
}